import { Dictionary } from "@/api/system-api/dictionary/types/dictionary"
import { getListByParentId } from "@/api/system-api/dictionary"
import { defineStore } from "pinia"
import { ref } from "vue"
import store from ".."
export const useDictionaryStore = defineStore("dictionary", () => {
  const dicMap = ref(new Map<number, Array<Dictionary>>())
  const refreshMap = new Map<number, boolean>()
  /**
   * 获取字典下拉列表的方法，调用此方法将会把不同父节点id的下拉项缓存下来，未刷新系统的情况下只会调用一次接口
   * @param parentId 父节点id
   * @param retryTime 如果多个相同组件需要同样的下拉项，每次尝试重新获取字典的延迟时间 毫秒
   * @returns Promise<Array<Dictionary>> 需要await
   */
  const getDicList = async (parentId: number, retryTime: number = 500): Promise<Array<Dictionary>> => {
    let refresh
    if (refreshMap.has(parentId)) {
      refresh = refreshMap.get(parentId)
    } else {
      refresh = false
      refreshMap.set(parentId, true)
    }
    if (!refresh) {
      let result = [] as Array<Dictionary>
      if (dicMap.value.has(parentId)) {
        result = dicMap.value.get(parentId)!
      } else {
        const temp = {
          parentId: parentId
        }
        await getListByParentId(temp).then((res) => {
          if (res.code === 2000) {
            result = res.items
            dicMap.value.set(parentId, result)
          }
        })
        refreshMap.set(parentId, false)
      }
      return result
    } else {
      return new Promise((resolve) => {
        setTimeout(async () => {
          resolve(await getDicList(parentId))
        }, retryTime)
      })
    }
  }
  return { dicMap, getDicList }
})
export function useDictionaryStoreHook() {
  return useDictionaryStore(store)
}
